<?php
/*
 * @Author: 天羽落星辰
 * @Date: 2020-08-14 14:55:03
 * @LastEditors: 天羽落星辰
 * @LastEditTime: 2020-08-17 11:23:22
 * @Description: file content
 */


namespace app\api\controller\nozzle;

use app\common\controller\Api;

/**
 * 授权码验证
 */
class Empower extends Api
{


    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];


    /**
     * 验证授权码
     *
     * @param string $apikey      授权码
     */
    public  function check_apikey($apikey = '')
    {


        try {
            if (!$apikey) {
                throw new \Exception("请输入授权码");
            }
            $row = db('nozzle_empower')->field(true)->where('apikey', $apikey)->find();
            if (!$row) {
                throw new \Exception("授权码不正确");
            }
            if ($row['end_time'] < time()) {
                throw new \Exception("授权码已过期，请联系管理员");
            }

            if ($row['white_list_ip']) {
                $white_list_ip = explode(',', $row['white_list_ip']);
                if (!in_array(request()->ip(), $white_list_ip)) {
                    throw new \Exception("该IP禁止请求");
                }
            }else{
                throw new \Exception('请设置你的白名单IP');
            }

        } catch (\Exception $e) {
            $this->error($e->getMessage());
            //throw $th;
        }

        $this->empower_log($row);
        return true;
    }


    // 日志记录
    private function empower_log($row)
    {   
        $empower_id = $row['id'];
        $ip = request()->ip();
        $method = request()->method();
        $param = request()->param();
        $action = request()->action();
        $createtime = time();

        $data = [
            'empower_id'    => $empower_id,
            'ip'            => $ip,
            'method'        => $method,
            'param'         => json_encode($param),
            'action'          => $action,
            'createtime'    => $createtime,
        ];
        db('nozzle_empower_log')->insert($data);
    }
}
